package group32.client;
import java.util.ArrayList;
import java.util.Iterator;

import group32.shared.User;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Registration extends Composite{
	int userid=-1;
	private RegistrationServiceAsync pService = GWT
	.create(RegistrationService.class);
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	
	private VerticalPanel mainPanel = new VerticalPanel();
	private VerticalPanel content = new VerticalPanel();
	  private HorizontalPanel msgPanel = new HorizontalPanel();
	  private HorizontalPanel addPanel = new HorizontalPanel();
	  private ListBox userType = new ListBox();
	  FormPanel register= new FormPanel();
	  final Label notifyLabel = new Label();
	  final Label titleLabel = new Label();
	  final Label errorLabel = new Label();
		final Button sendButton = new Button("Register");
		final Button resetButton = new Button("Reset");
		final TextBox nameField = new TextBox();
		final TextBox firstName = new TextBox();
		final TextBox lastName = new TextBox();
		final TextBox yrsAdv = new TextBox();
		final TextBox email = new TextBox();
		final PasswordTextBox password = new PasswordTextBox();
		final PasswordTextBox chkPassword = new PasswordTextBox();

		
	/**
	 * This is the entry point method.
	 */
	public Registration() {
		
		History.newItem("register");
		
		register.addStyleName("table-center");
		Window.setTitle("PennPhoto::Register User");		
		// We can add style names to widgets
		sendButton.addStyleName("sendButton");
	    userType.addItem("Professor");
	    userType.addItem("Student");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		
		addPanel.setVerticalAlignment(HorizontalPanel.ALIGN_BOTTOM);
		addPanel.add(sendButton);
		addPanel.add(resetButton);
		
	
		mainPanel.add(new Label("Please enter a username:"));
		mainPanel.add(nameField);		
		mainPanel.add(new Label("Enter a password:"));
		mainPanel.add(password);
		mainPanel.add(new Label("Re-enter your password:"));
		mainPanel.add(chkPassword);
		mainPanel.add(new Label("Please enter your firstname:"));
		mainPanel.add(firstName);
		mainPanel.add(new Label("Please enter your lastname:"));
		mainPanel.add(lastName);
		mainPanel.add(new Label("Please enter your email:"));
		mainPanel.add(email);
		mainPanel.add(new Label("Select a user category:"));
		mainPanel.add(userType);
		DOM.setInnerHTML(msgPanel.getElement(),"</div>"+
		        "<div colspan='2' style='color:red;' id='errorLabelContainer'>");
		msgPanel.add(errorLabel);
		// Focus the cursor on the name field when the app loads
		mainPanel.addStyleName("paddedHorizontalbottom");
		nameField.setFocus(true);
		nameField.selectAll();
		register.add(mainPanel);
		content.add(register);
		content.add(addPanel);
		content.add(msgPanel);
		initWidget(content);

	
		// Add a handler to add a user
		sendButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				char ut;
				if(userType.getItemText(userType.getSelectedIndex()).equals("Student"))
					ut='S';
				else
					ut='P';
				User u=new User();
				u.username=nameField.getText();
				u.password=password.getText();
				u.firstname=firstName.getText();
				u.lastname=lastName.getText();
				u.email=email.getText();
				u.usertype=ut;
				saveUser(u);
			}
		});

		sendButton.addKeyPressHandler(new KeyPressHandler() {
			
			@Override
			public void onKeyPress(KeyPressEvent event) {
				char ut;
				if(userType.getItemText(userType.getSelectedIndex()).equals("Student"))
					ut='S';
				else
					ut='P';
						User u=new User();
						u.username=nameField.getText();
						u.password=password.getText();
						u.firstname=firstName.getText();
						u.lastname=lastName.getText();
						u.email=email.getText();
						u.usertype=ut;
						saveUser(u);
			}
			
		});
		

	
		resetButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
			resetFields();
			}
		});

	}
	
	
	private void resetFields(){
		nameField.setText("");
		firstName.setText("");
		lastName.setText("");
		password.setText("");
		chkPassword.setText("");
		email.setText("");
		userType.setSelectedIndex(0);
		nameField.setFocus(true);
	}    
	
	public String greetServer(String name) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		return null;
	}
	  /**
	   * Add user to the db. Executed when the user clicks the register button or
	   * presses enter.
	   */
	  public boolean saveUser(User u)
			  throws IllegalArgumentException {

		  final boolean success=false;
		  
		  notifyLabel.setText("Sending Data....");
		  //msgPanel.add(notifyLabel);
		 // RootPanel.get("notificationContainer").add(notifyLabel);

	    // TODO Auto-generated method stub
          pService.saveUser(u, new AsyncCallback<Boolean>() {
                  public void onSuccess(Boolean result) {
                	  //resetFields();
                	  //RootPanel.get("notificationContainer").clear();
                	  Window.alert("User has been successfully saved");
                	  FlowControl.go(new Login());
                	  //boolean success=result;
            		 // notifyLabel.setText("User has been successfully saved");
                  }
                  
                  public void onFailure(Throwable caught) {
                	  //RootPanel.get("notificationContainer").clear();
            		  errorLabel.setText("There was an error saving to database");
            		  //RootPanel.get("notificationContainer").add(errorLabel);
                  }
                 
                  
          });
          return success;
	  }
}
